/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 23:16:25
 * @Last modified by:   ls-mac
 * @Last modified time: 2019-08-23 12:46:22
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  TimePicker,
  Table,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
} from 'antd';
import SimpleTable from 'components/SimpleTable';
import styles from './enterprise.less';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const FormItem = Form.Item;

const CreateForm = Form.create()(prop => {
  const { state, form, props, handleCancel, renderOptionsP } = prop;
  const { modalVisible, type, record } = state;
  const { getFieldDecorator } = form;
  const { dispatch } = props;

  const detailInfo = record;

  const handleOk = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {
        ...fieldsValue,
      };
      if (detailInfo) {
        params.id = detailInfo.id;
      }
      dispatch({
        type: 'cityList/dictCityAddOrEdit',
        payload: params,
        callback: res => {
          if (res.success) {
            message.success(type === 'add' ? '新增城市成功' : '修改城市成功');
            handleCancel();
          } else {
            message.info(res.errorDesc);
          }
        },
      });
    });
  };

  return (
    <Modal
      title={type === 'add' ? '新增城市' : '修改城市'}
      visible={modalVisible}
      onOk={() => handleOk()}
      onCancel={() => handleCancel()}
      className=""
      okText="提交"
      width="300px"
      destroyOnClose
    >
      <Form layout="inline">
        <Row gutter={{ lg: 24 }}>
          <Col md={24} sm={24}>
            <FormItem label="省份名称">
              {getFieldDecorator('provinceId', {
                initialValue: detailInfo?.provinceId,
                rules: [{ required: true, message: '请选择省份' }],
              })(
                <Select
                  showSearch
                  placeholder="请选择"
                  style={{ width: 150 }}
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {renderOptionsP()}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ lg: 24 }}>
          <Col md={24} sm={24}>
            <FormItem label="城市名称">
              {getFieldDecorator('name', {
                initialValue: detailInfo?.name,
                rules: [{ required: true, message: '请输入省份名称' }],
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ lg: 24 }}>
          <Col md={24} sm={24}>
            <FormItem label="&nbsp;&nbsp;&nbsp;排序&#12288;&#12288;">
              {getFieldDecorator('sort', {
                initialValue: detailInfo?.sort,
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
});

@connect(({ cityList, dict, loading }) => ({
  modalVisible: false,
  cityList,
  dict,
  loading: loading.models.cityList,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    type: 'add',
    record: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'cityList/fetch',
      payload: {
        name: '',
        pageIndex: '1',
        pageSize: '10',
      },
    });
    // 查询省份
    dispatch({
      type: 'dict/dictProvinceList',
      payload: {},
    });
  }

  // 分页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const params = {
        pageIndex: pagination.current,
        pageSize: pagination.pageSize,
        name: values.name,
      };

      dispatch({
        type: 'cityList/fetch',
        payload: params,
      });
    });
  };

  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'cityList/fetch',
      payload: {
        name: '',
        pageIndex: '1',
        pageSize: '10',
      },
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      const params = {
        pageIndex: 0,
        pageSize: 10,
        name: values.name,
      };

      dispatch({
        type: 'cityList/fetch',
        payload: params,
      });
    });
  };

  handleEdit = record => {
    this.setState({
      type: 'edit',
      modalVisible: true,
      record,
    });
  };

  handleCancel = () => {
    this.setState({
      modalVisible: false,
    });
    this.handleFormReset();
  };

  handleAdd = () => {
    this.setState({
      modalVisible: true,
    });
  };

  handleDelete = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'cityList/dictCityDelete',
      payload: { id: record.id },
      callback: res => {
        if (res.success) {
          message.success('删除成功');
        } else {
          message.info(res.errorDesc);
        }
        this.handleFormReset();
      },
    });
  };

  reColumns = () => {
    const that = this;

    return [
      {
        title: '省份名称',
        dataIndex: 'provinceId',
      },
      {
        title: '城市名称',
        dataIndex: 'name',
      },
      {
        title: '排序',
        dataIndex: 'sort',
      },
      {
        title: '操作',
        render: (val, record) => (
          <div>
            <a onClick={() => that.handleEdit(record)}>修改</a>
            <br />
            <Popconfirm title="确认删除?" onConfirm={() => that.handleDelete(record)}>
              <a>删除</a>
            </Popconfirm>
          </div>
        ),
      },
    ];
  };

  renderOptionsP = () => {
    const {
      dict: { provinceList },
    } = this.props;
    const options = provinceList.map(v => <Option value={v.id}>{v.name}</Option>);
    return options;
  };

  renderSearchForm = () => {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={8} sm={24}>
            <FormItem label="城市名称">
              {getFieldDecorator('name')(<Input placeholder="请输入城市名称" />)}
            </FormItem>
          </Col>
          <Col md={16} sm={24}>
            <div
              style={{
                overflow: 'hidden',
                height: '40px',
                lineHeight: '40px',
              }}
            >
              <span
                style={{
                  float: 'right',
                }}
              >
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  style={{
                    marginLeft: 8,
                  }}
                  onClick={this.handleFormReset}
                >
                  重置
                </Button>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const columns = this.reColumns();
    const {
      cityList: { data },
      loading,
    } = this.props;

    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }}>
          <div>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
            <div>
              <Button type="primary" icon="plus" onClick={this.handleAdd}>
                新增
              </Button>
            </div>
            <SimpleTable
              selectedRows={false}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={false}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...this} />
      </PageHeaderLayout>
    );
  }
}
